package com.wds.service.impl;


import com.google.gson.Gson;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.wds.domain.JsonResult;
import com.wds.exception.CustomException;
import com.wds.service.OssUploadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.UUID;

/**
 * @author WDs , wds8.24@outlook.com
 * @version 1.0
 * @since 2022-11-11 15:18
 */
@Slf4j
@Service
public class OssUploadServiceImpl implements OssUploadService {

    @Value("${oss.ak}")
    private String ak;
    @Value("${oss.sk}")
    private String sk;
    @Value("${oss.bucket}")
    private String bucket;
    @Value("${oss.domainName}")
    private String domainName;

    //工具方法 上传文件
    private DefaultPutRet uploadFile(String key, MultipartFile file) {
        Configuration cfg = new Configuration(Region.huabei());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
        cfg.useHttpsDomains = false;

        Auth auth = Auth.create(ak, sk);
        String token = auth.uploadToken(bucket);

        UploadManager uploadManager = new UploadManager(cfg);
        Response response = null;
        DefaultPutRet putRet = null;
        try {

            response = uploadManager.put(file.getInputStream(), key, token, null, null);
            putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);

        } catch (IOException e) {
            log.info("OSS上传文件失败: {}", key);
            e.printStackTrace();
        }

        return putRet;
    }


    /**
     * 上传图片文件，仅支持 jpg png jpeg
     * 1.判断文件格式
     * 2.生成文件路径和UUID文件名
     * 3.上传文件
     * 4.处理上传结果
     * 5.返回完整路径
     * @param file 文件
     * @return 文件全路径
     */
    @Override
    public JsonResult<String> uploadImg(MultipartFile file) {
        //check file size   application.yml

        String name = file.getOriginalFilename();
        if (name == null) {
            throw new CustomException("文件名异常");
        }
        //文件名转小写
        name = name.toLowerCase(Locale.ROOT);
        String key = "";
        //检查文件格式
        String fileType = name.substring(name.lastIndexOf('.'));
        if (fileType.equals(".png") || fileType.equals(".jpg") || fileType.equals(".jpeg")) {
            //设置新文件名  和 oss 文件路径   格式: 年/月/日/UUID.type
            SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd/");
            key = format.format(new Date()) + UUID.randomUUID() + fileType;
        } else {
            throw new CustomException("图片格式仅支持png、jpg、jpeg。");
        }


        DefaultPutRet putRet = this.uploadFile(key, file);
        if (putRet == null) {
            return JsonResult.fail("上传失败!");
        }
        log.info("上传文件成功：{}", putRet.key);
        return JsonResult.ok(domainName + putRet.key);
    }
}
